package clickhouse

import (
	"flag"
	"fmt"
	"gitee.com/mootok/mootok/src/constant/config"
	"gitee.com/mootok/mootok/src/utils/logging"
	"gorm.io/driver/clickhouse"
	"gorm.io/gorm"
	"time"
)

var Client *gorm.DB

func init() {
	logger := logging.LogService("Clickhouse.Init")
	var err error
	var cfg gorm.Config
	var dsn = fmt.Sprintf("clickhouse://%s:%s@%s:%s/%s?dial_timeout=30s&read_timeout=30s",
		config.EnvConfig.ClickhouseUser,
		config.EnvConfig.ClickhousePassword,
		config.EnvConfig.ClickhouseHost,
		config.EnvConfig.ClickhousePort,
		config.EnvConfig.ClickhouseDatabase)

	if flag.Lookup("test.v") != nil {
		logger.Info("skip clickhouse init in testing mode")
		return
	}

	Client, err = gorm.Open(clickhouse.Open(dsn), &cfg)

	sqlDB, err := Client.DB()
	if err != nil {
		panic(err)
	}

	sqlDB.SetMaxIdleConns(100)
	sqlDB.SetMaxOpenConns(200)
	sqlDB.SetConnMaxLifetime(24 * time.Hour)
	sqlDB.SetConnMaxIdleTime(time.Hour)

}
